package com.viboo.concern.controller;

import com.google.gson.Gson;
import com.viboo.concern.entity.ChatCode;
import com.viboo.concern.entity.Rank;
import com.viboo.concern.entity.User;
import com.viboo.concern.response.Result;
import com.viboo.concern.response.ResultEnum;
import com.viboo.concern.response.ResultUtil;
import com.viboo.concern.service.impl.RankServiceImpl;
import com.viboo.concern.service.impl.UserServiceImpl;
import com.viboo.concern.util.Constants;
import com.viboo.concern.util.NetHttpClient;
import com.viboo.concern.util.TextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author avanline
 * @descriotion
 * @date 2018-02-28 18:40
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Autowired
    UserServiceImpl userService;

    @Autowired
    RankServiceImpl rankService;

    @GetMapping("add")
    Result<?> add(User user, Rank rank) {
        rank.setUserAvatar(user.getAvatar());
        log.info(user.toString() + "--------" + rank.toString());
        Result mUserResult = addUser(user);
        Result mRankResult = addRank(rank);
        if (mUserResult.getCode() == ResultEnum.SUCCESS.getCode() && mRankResult.getCode() == ResultEnum.SUCCESS.getCode()) {
            User mUser = null;
            try {
                mUser = userService.selectUser(rank.getUserId());
                if (mUser == null)
                    return ResultUtil.error("不存在被关注人信息");
                mUser.setUserName(URLDecoder.decode(mUser.getUserName(), "utf-8"));
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error();
            }
            return ResultUtil.success(mUser);

        } else {
            if (mUserResult.getCode() == ResultEnum.SUCCESS.getCode())
                return mRankResult;
            else
                return mUserResult;
        }
    }

    private Result<?> addRank(Rank rank) {
        if (TextUtils.isEmpty(rank.getOpenId()))
            return ResultUtil.error("rank用户ID为空");
        if (TextUtils.isEmpty(rank.getUserId()))
            return ResultUtil.error("关注人ID为空");
        if (TextUtils.isEmpty(rank.getUserName()))
            return ResultUtil.error("用户昵称为空");
        if (TextUtils.isEmpty(rank.getUserAvatar()))
            return ResultUtil.error("用户头像为空");
        if (rank.getOpenId().equals(rank.getUserId()))
            return ResultUtil.success();
        try {
            rank.setUserName(URLEncoder.encode(rank.getUserName(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            rank.setEntryTime(System.currentTimeMillis());
            if (rankService.addRank(rank))
                return ResultUtil.success();
            else
                return ResultUtil.error(ResultEnum.FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    /***
     * 插入用户信息
     * @param user
     * @return
     */
    private Result<?> addUser(User user) {
        if (TextUtils.isEmpty(user.getOpenId()))
            return ResultUtil.error("user用户ID为空");
        if (TextUtils.isEmpty(user.getUserName()))
            return ResultUtil.error("用户昵称为空");
        if (TextUtils.isEmpty(user.getAvatar()))
            return ResultUtil.error("用户头像为空");

        try {
            user.setUserName(URLEncoder.encode(user.getUserName(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        user.setShareTime(0L);
        try {
            if (userService.addUser(user))
                return ResultUtil.success();
            else
                return ResultUtil.error(ResultEnum.FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    @GetMapping("update/share/time")
    Result<?> updateShareTime(User user) {
        if (TextUtils.isEmpty(user.getOpenId()))
            return ResultUtil.error("用户ID为空");
        try {
            User mUser = userService.selectUser(user.getOpenId());
            if (mUser.getShareTime() != 0)
                return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (userService.updateShareTime(user))
                return ResultUtil.success();
            else
                return ResultUtil.error(ResultEnum.FAIL);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    @GetMapping("select")
    Result<?> selectUser(User user) {
        if (TextUtils.isEmpty(user.getOpenId()))
            return ResultUtil.error("用户ID为空");
        try {
            User mUser = userService.selectUser(user.getOpenId());
            if (mUser != null)
                return ResultUtil.success();
            else
                return ResultUtil.error(ResultEnum.FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }

    @GetMapping("chat")
    Result<?> getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> map = new HashMap<>();
        map.put("appid", Constants.APP_ID);
        map.put("secret", Constants.APP_SECRET);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        try {
            String mValue = NetHttpClient.sendGet(url, map);
            ChatCode mChatCode = new Gson().fromJson(mValue, ChatCode.class);
            return ResultUtil.success(mChatCode);
        } catch (Exception e) {
            return ResultUtil.error("获取code报错");
        }
    }
}
